const fs = require('fs')
const chalk = require('chalk')
const args = require('minimist')(process.argv.slice(2))
const path = require('path')
const { packages } = require('../util')

const targets = fs.readdirSync(packages).filter(f => {
  const file = path.join(packages, f)
  // 如果不是文件夹证明不是项目
  if (!fs.statSync(file).isDirectory()) {
    return false
  }
  // 如果是 private 证明不打包不发布
  const pkg = require(path.join(file, 'package.json'))
  if (pkg.private) {
    return false
  }
  return true
})
/**
 * 过滤可以被打包或者 dev 的项目
 * @param {string[]} partialTargets
 * @returns
 */
const fuzzyMatchTarget = partialTargets => {
  const matched = []
  partialTargets.forEach(partialTarget => {
    for (const target of targets) {
      if (target.match(partialTarget)) {
        matched.push(target)
      }
    }
  })
  if (matched.length) {
    return matched
  } else {
    console.log()
    console.error(
      `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(
        `Target ${chalk.underline(partialTargets)} not found!`
      )}`
    )
    console.log()

    process.exit(1)
  }
}
exports.args = args
exports.targets = targets
exports.formats = args.formats || args.f
// exports.sourceMap = args.sourcemap || args.s
exports.target = args._.length ? fuzzyMatchTarget(args._)[0] : ''
